package mc.contents.web.common;

import mc.contents.service.ICrawService;
import mc.contents.web.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by Administrator on 14-12-8.
 */
public class AbstractRequestHttpServlet extends HttpServlet{
    private static Logger log = LoggerFactory.getLogger( AbstractRequestHttpServlet.class );
    public ICrawService crawService;
    public CrawConfig crawConfig;
    protected AtomicLong atomicId = new AtomicLong( 0 );

    @Override
    public void init( ServletConfig config ) throws ServletException {
        super.init( config );
        ServletContext servletContext = config.getServletContext();
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext( servletContext );
        crawService = (ICrawService) context.getBean( "crawService" );
        crawConfig = (CrawConfig) context.getBean( "crawConfig" );
    }

    @Override
    protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
        super.doPost( req, resp );
    }

    public void paramsNeed( HttpServletResponse res,String... params ){
        boolean paramEmpty = false;
        for ( String param : params ) {
            if( StringUtils.isEmpty( param )){
                paramEmpty = true;
                break;
            }
        }
        if( paramEmpty ){
            String msg = "params is need !";
            responseFront(200,msg,res);
        }
    }

    public void responseFront( int status,String msg, HttpServletResponse res){
        try{
            res.setStatus( status );
            res.setHeader( "Content-type","text/javascript;charset=UTF-8" );
            PrintWriter writer = res.getWriter();
            writer.print( msg );
            writer.flush();
        }catch ( IOException e ){
            log.error( "responseSuccess error : ",e );
        }
    }
}
